package cn.i7baozh.boot.learn.thirdproperty;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.config.ConfigData;
import org.springframework.boot.context.config.ConfigDataLoader;
import org.springframework.boot.context.config.ConfigDataLoaderContext;
import org.springframework.boot.context.config.ConfigDataResourceNotFoundException;
import org.springframework.boot.env.OriginTrackedMapPropertySource;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 加载配置
 * @author zhangbaoqi532
 * @date 2025/2/24
 */
@Slf4j
public class MyConfigDataLoader implements ConfigDataLoader<MyPropertyDataResource> {

    @Override
    public boolean isLoadable(ConfigDataLoaderContext context, MyPropertyDataResource resource) {
        return ConfigDataLoader.super.isLoadable(context, resource);
    }

    //加载远程数据库的配置
    @Override
    public ConfigData load(ConfigDataLoaderContext context, MyPropertyDataResource resource) throws IOException, ConfigDataResourceNotFoundException {

        //因为我已经在resolver里实例化了所以这里一定能获取到，否则要判断下
        MyConfigDataService myConfigDataService = context.getBootstrapContext().get(MyConfigDataService.class);
        //resource也是在resolver流程里初始化过的
        String tableName = resource.getTableName();
        //模拟从数据库取配置
        Map<String, Object> dbTableConfig = myConfigDataService.getConfigByTableName(tableName, resource.getProfiles());
        if (dbTableConfig == null || dbTableConfig.isEmpty()) {
            return null;
        }
        //组装数据
        OriginTrackedMapPropertySource source = new OriginTrackedMapPropertySource(tableName,
                dbTableConfig);

        //这个options没看懂，是从nacos拷贝过来的
        List<ConfigData.Option> options = new ArrayList<>();
        options.add(ConfigData.Option.IGNORE_IMPORTS);
        options.add(ConfigData.Option.IGNORE_PROFILES);
        options.add(ConfigData.Option.PROFILE_SPECIFIC);
        return new ConfigData(List.of(source),options.toArray(new ConfigData.Option[0]));
    }
}
